import time
import logging

from utils.threadpool import init_thread_pool, async_thread

# 初始化日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Notice 初始化线程池：最多 2 个线程，等待队列只能容纳 3 个任务
init_thread_pool(max_workers=2, qsize=3)


# Notice 设置 raise_error=True，当等待队列满的时候会记录 error_log
@async_thread
def dummy_task(task_id, delay=2, raise_error=True):
    logger.info(f"[task {task_id}] start")
    time.sleep(delay)
    logger.info(f"[task {task_id}] end")

    return task_id


# Notice 并发地执行 dummy_task，测试等待队列满了的情况～
def main():
    tasks = []
    for i in range(10):
        try:
            logger.info(f"Submitting task {i}")
            # 注意这里传 raise_error=True 或 False
            future = dummy_task(i, delay=2, raise_error=True)
            tasks.append(future)
        except Exception as e:
            logger.error(f"Task {i} failed to submit: {e}")

    # 等待所有任务完成（仅用于测试观察效果）
    for i, f in enumerate(tasks):
        try:
            if hasattr(f, 'result'):
                # 等待执行完成
                ret = f.result()
                print(f'Task {i}: result: {ret}')
        except Exception as e:
            logger.error(f"[task {i}] Exception during result(): {e}")


if __name__ == "__main__":
    main()
